package com.cardbaobao.cardbabyclient.ui.fragment.card;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.cardbaobao.cardbabyclient.R;
import com.cardbaobao.cardbabyclient.api.Api;
import com.cardbaobao.cardbabyclient.base.BaseResult;
import com.cardbaobao.cardbabyclient.base.Constant;
import com.cardbaobao.cardbabyclient.buried.Self;
import com.cardbaobao.cardbabyclient.buried.SelfUtils;
import com.cardbaobao.cardbabyclient.model.RealName;
import com.cardbaobao.cardbabyclient.model.UserBindCards;
import com.cardbaobao.cardbabyclient.model.result.HasBindCardResult;
import com.cardbaobao.cardbabyclient.ui.activity.AddCreditCardActivity;
import com.cardbaobao.cardbabyclient.ui.activity.BankCardManageActivity;
import com.cardbaobao.cardbabyclient.ui.activity.BankCardVerifyActivity;
import com.cardbaobao.cardbabyclient.ui.activity.IdentifyVerifyActivity;
import com.cardbaobao.cardbabyclient.ui.adapter.CreditCardAdapter;
import com.cardbaobao.cardbabyclient.ui.dialog.DebitSuggestionDialog;
import com.cardbaobao.cardbabyclient.ui.dialog.UnbindCardDialog;
import com.cardbaobao.cardbabyclient.ui.fragment.base.BaseFragment;
import com.cardbaobao.cardbabyclient.utils.ApplicationHelper;
import com.cardbaobao.cardbabyclient.utils.JsonUtil;
import com.cardbaobao.cardbabyclient.utils.ToastUtil;
import com.cardbaobao.cardbabyclient.widget.divider.VerticalItemDecoration;
import com.scwang.smartrefresh.layout.util.DensityUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import rx.Subscriber;

/**
 * Created by Jiangzx on 2017/9/14 9:20.
 */

public class CreditCardFragment extends BaseFragment {
    private String prePageId;
    public void setBuriedData(String prePageId){
        this.prePageId=prePageId;
    }
    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_credit_card;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void initViewFinish(View view, Bundle savedInstanceState) {

        mCurrentPageId= Self.Page.app_credit_card_page;

        LinearLayoutManager layoutManager=
                new LinearLayoutManager(mContext,LinearLayoutManager.VERTICAL,false);
        VerticalItemDecoration decoration=new VerticalItemDecoration(0, DensityUtil.dp2px(15));
        recyclerView.addItemDecoration(decoration);
        recyclerView.setLayoutManager(layoutManager);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    public void setData(List<UserBindCards.CreditCard> cards){
        List<CreditCardAdapter.CreditCardItem> data=new ArrayList<>();
        if(cards!=null&&cards.size()>0){
            for(int i=0,length=cards.size();i<length;i++){
                data.add(new CreditCardAdapter.CreditCardItem(CreditCardAdapter.TYPE_ITEM,
                        cards.get(i)));
            }
            data.add(new CreditCardAdapter.CreditCardItem(CreditCardAdapter.TYPE_ADD,null));
        }else{
            data.add(new CreditCardAdapter.CreditCardItem(CreditCardAdapter.TYPE_NO_CARD,null));
            data.add(new CreditCardAdapter.CreditCardItem(CreditCardAdapter.TYPE_ADD,null));
        }
        CreditCardAdapter adapter=new CreditCardAdapter(mContext,data);
        adapter.setCreditCardAction(new CreditCardAdapter.CreditCardAction() {
            @Override
            public void onCreditCardAction(int action,UserBindCards.CreditCard card) {
                switch (action){
                    case CreditCardAdapter.CreditCardAction.ACTION_UNBIND:
                        showUnBindDialog(card.getCredit_card_name(),
                                card.getCredit_card_no());
                        break;
                    case CreditCardAdapter.CreditCardAction.ACTION_ADD_CARD:
                        //需要先添加储蓄卡才能添加信用卡
                        SelfUtils.buriedClickData(Self.Action.app_click_credit_card_add,
                                Self.Action.app_click_credit_card_add_des,
                                mEnterPageTime,
                                mCurrentPageId,
                                prePageId);
                        checkBindCard();
                        break;
                }
            }
        });
        recyclerView.setAdapter(adapter);
    }

    DebitSuggestionDialog debitDialog;
    private void showBindDebitCardDialog(final String realName,final String idCardNo){
        if(debitDialog==null){
            debitDialog=new DebitSuggestionDialog(mContext);
            debitDialog.setTitleText("温馨提示");
            debitDialog.setMessageText("添加信用卡前，请先绑定储蓄卡");
            debitDialog.setTvCancelText("取消");
            debitDialog.setTvEnsureText("去绑定");
            debitDialog.setCanceledOnTouchOutside(false);
        }
        debitDialog.setClickedListener(new DebitSuggestionDialog.ClickedListener() {
            @Override
            public void onEnsureClicked() {
                Intent intent=new Intent(mContext,IdentifyVerifyActivity.class);
                intent.putExtra(IdentifyVerifyActivity.NAME_S,
                        realName);
                intent.putExtra(IdentifyVerifyActivity.ID_CARD_NO_S,
                        idCardNo);
                intent.putExtra(BankCardVerifyActivity.PAGE_FROM_I,
                        BankCardVerifyActivity.ACTIVITY_CARD_MANAGE_ADD);
                startActivity(intent);
            }
        });
        if(!debitDialog.isShowing()){
            debitDialog.show();
        }
    }

    private void startAddCreditCard(String realName,String idCardNo){
        Intent intent=new Intent();
        intent.setClass(mContext, AddCreditCardActivity.class);
        intent.putExtra(AddCreditCardActivity.NAME_S,realName);
        intent.putExtra(AddCreditCardActivity.ID_CARD_NO_S,idCardNo);
        intent.putExtra(AddCreditCardActivity.PAGE_FROM_I,
                AddCreditCardActivity.PAGE_BANK_CARD_MANAGE);
        startActivity(intent);
        getActivity().finish();
    }

    private void checkBindCard(){
        showProgressDialog(false);
        Api.checkBindCard(String.valueOf(mApplication.getUser().getID())).
                subscribe(new Subscriber<String>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable throwable) {
                dismissProgressDialog();
                ToastUtil.showToast(ApplicationHelper.
                        getApplicationContext().
                        getString(R.string.string_request_server_fail));
            }

            @Override
            public void onNext(String s) {
                dismissProgressDialog();
                HasBindCardResult result=JsonUtil.json2Object(s,HasBindCardResult.class);
                if(result.getCode()==0){
                    if(result.getMsg().contains("未实名认证")){
                        Intent intent=new Intent();
                        intent.setClass(mContext, IdentifyVerifyActivity.class);
                        intent.putExtra(BankCardVerifyActivity.PAGE_FROM_I,
                                BankCardVerifyActivity.ACTIVITY_CARD_MANAGE_ADD);
                        startActivity(intent);
                    }else{
                        ToastUtil.showToast(result.getMsg());
                    }
                }else if(result.getCode()==1){
                    RealName realName=result.getData();
                    startAddCreditCard(realName.getTrue_name(),realName.getId_card_no());
                }else if(result.getCode()==2){
                    //添加储蓄卡
                    RealName realName=result.getData();
                    showBindDebitCardDialog(realName.getTrue_name(),
                            realName.getId_card_no());
                }else if(result.getCode()==3){
                    //添加信用卡
                    RealName realName=result.getData();
                    startAddCreditCard(realName.getTrue_name(),realName.getId_card_no());
                }
            }
        });
    }

    private void unBindCreditCard(String cardNumber){
        showProgressDialog(false);
        Api.unBindCreditCard(cardNumber,
                String.valueOf(mApplication.getUser().getID())).
                subscribe(new Subscriber<String>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable throwable) {
                        dismissProgressDialog();
                        ToastUtil.showToast(ApplicationHelper.getApplicationContext().
                                getString(R.string.string_request_server_fail));
                    }

                    @Override
                    public void onNext(String s) {
                        dismissProgressDialog();
                        BaseResult result= JsonUtil.json2Object(s,BaseResult.class);
                        if(result.getCode()== Constant.SUC_CODE){
                            //解绑成功
                            Activity activity=getActivity();
                            if(activity instanceof BankCardManageActivity){
                                ((BankCardManageActivity)activity).loadData();
                            }
                        }else{
                            ToastUtil.showToast(result.getMsg());
                        }
                    }
                });
    }

    //解绑储蓄卡
    private void showUnBindDialog(String cardName,final String cardNumber){
        final UnbindCardDialog dialog=
                new UnbindCardDialog(getActivity(),
                        "您正在解绑--"+
                                cardName+
                                "信用卡("+
                                cardNumber.substring(cardNumber.length()-4)+
                                ")");
        dialog.setClickedListener(new UnbindCardDialog.ClickedListener() {
            @Override
            public void onEnsureClicked() {
                dialog.dismiss();
                SelfUtils.buriedClickData(Self.Action.app_click_credit_card_unbind,
                        Self.Action.app_click_credit_card_unbind_des,
                        mEnterPageTime,
                        mCurrentPageId,
                        prePageId);
                unBindCreditCard(cardNumber);
            }
        });
        dialog.show();
    }
}
